import { NextRequest, NextResponse } from 'next/server'
import { changePassword } from '@/lib/auth-service'
import { requireAuth, withErrorHandling } from '@/lib/auth-middleware'

export const POST = withErrorHandling(async (request: NextRequest) => {
  return requireAuth(request, async (req) => {
    try {
      const { currentPassword, newPassword } = await request.json()
      const userId = req.user?.id

      if (!userId) {
        return NextResponse.json(
          { error: '用户未登录' },
          { status: 401 }
        )
      }

      const result = await changePassword(userId, currentPassword, newPassword)

      if (result.success) {
        return NextResponse.json({
          success: true,
          message: '密码修改成功'
        })
      } else {
        return NextResponse.json({
          success: false,
          error: result.error
        }, { status: 400 })
      }
    } catch (error) {
      console.error('修改密码API错误:', error)
      return NextResponse.json({
        success: false,
        error: '服务器内部错误'
      }, { status: 500 })
    }
  })
})
